package com.tianhui.consignortwofei.mvp.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.CommonUtil;
import com.fgs.common.utils.ToastUtil;
import com.google.gson.Gson;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.mvp.model.DriverModel;
import com.tianhui.consignortwofei.mvp.model.QuotationListBean;
import com.tianhui.consignortwofei.mvp.model.enty.EventQuotationPaiHaoBean;
import com.tianhui.consignortwofei.mvp.ui.adapter.QuotationDetailItemTwoAdapter;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;
import org.yczbj.ycrefreshviewlib.item.RecycleViewItemLine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/4/28
 * @description
 **/
public class AddQuotationDetailActivity extends BaseActivity {

    @BindView(R.id.rl_back)
    RelativeLayout rl_back;
    @BindView(R.id.tv_right_text)
    TextView tv_right_text;

    @BindView(R.id.tv_title_middle)
    TextView tv_title_middle;

    @BindView(R.id.tv_right_text_two)
    TextView tv_right_text_two;
    @BindView(R.id.et_baojia_text)
    EditText et_baojia_text;
    @BindView(R.id.et_beizhu_text)
    EditText et_beizhu_text;
    @BindView(R.id.rv_select_body)
    RecyclerView rv_select_body;

    @BindView(R.id.tv_updata)
    TextView tv_updata;


    private QuotationListBean.QuotationRecords quotationRecords;
    private QuotationDetailItemTwoAdapter detailItemAdapter;
    private DriverModel driverModel;
    private int lookType;

    @Override
    public int getLayoutId() {
        return R.layout.activity_quotation_detail;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public void init() {
        getToolbarStatus().isShowToolbar(false);
//        setTitle("详情");


        tv_title_middle.setText("报价详情");

        driverModel = new DriverModel();



        Bundle bundle = getIntent().getExtras();
        if (null!=bundle&&!TextUtils.isEmpty(bundle.getString("quatationDetail"))) {//null!=quatationDetailItem&& !TextUtils.isEmpty(quatationDetailItem)
            String quatationDetail = bundle.getString("quatationDetail");
            Gson gson = new Gson();
            quotationRecords = gson.fromJson(quatationDetail, QuotationListBean.QuotationRecords.class);

        }else {
            List<QuotationListBean.QuotationRecords.PlasticsQuotationListDTO> plasticsQuotationList=new ArrayList<>();
            quotationRecords=new QuotationListBean.QuotationRecords();
            quotationRecords.setPlasticsQuotationList(plasticsQuotationList);
        }

        lookType = bundle.getInt("lookType",2);
        if (2== lookType){
            tv_right_text.setVisibility(View.GONE);
            tv_right_text_two.setVisibility(View.GONE);
            et_baojia_text.setFocusable(false);
            et_beizhu_text.setFocusable(false);
            tv_updata.setVisibility(View.GONE);
        }



        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_select_body.setLayoutManager(linearLayoutManager);
        detailItemAdapter = new QuotationDetailItemTwoAdapter(this,quotationRecords.getPlasticsQuotationList(),lookType);
        rv_select_body.setAdapter(detailItemAdapter);
        RecycleViewItemLine line = new RecycleViewItemLine(this,
                LinearLayoutManager.HORIZONTAL,
                (int) CommonUtil.convertDpToPixel(10),
                getResources().getColor(R.color.colorLineGray));
        rv_select_body.addItemDecoration(line);
//      homeListAdapter.clear();
//      homeListAdapter.addAll(listBean.getDetails());



        changeView();



        detailItemAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (1== lookType) {
                    goPaiHao(position);
                }

            }
        });
        detailItemAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                switch (view.getId()){
                    case R.id.tv_change:
                        goPaiHao(position);
                        break;
                    case R.id.tv_delete:
                        deleteDiaLog(position);

                        break;
                }
            }
        });

    }

    private void goPaiHao(int position) {
        QuotationListBean.QuotationRecords.PlasticsQuotationListDTO driverInfo =
                (QuotationListBean.QuotationRecords.PlasticsQuotationListDTO) detailItemAdapter.getAllData().get(position);
        Gson gson=new Gson();
        String json = gson.toJson(driverInfo);
        Bundle bundle=new Bundle();
        bundle.putString("quatationDetailItem",json);
        openActivity(PaiHaoActivity.class, bundle);
    }

    private void changeView() {
        et_baojia_text.setText(quotationRecords.getContent());
        et_beizhu_text.setText(quotationRecords.getRemarks());

        detailItemAdapter.clear();
        detailItemAdapter.addAll(quotationRecords.getPlasticsQuotationList());
    }

    @Override
    public BaseFragment createFragment() {
        return null;
    }

    @OnClick(R.id.rl_back)
    public void close() {
        finish();
    }

    @OnClick(R.id.tv_right_text)
    public void rightText() {
        openActivity(PaiHaoActivity.class);

    }

    @OnClick(R.id.tv_right_text_two)
    public void textTwo() {
        getLastBaoJia();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventQuotationPaiHaoBean event) {
        switch (event.getType()){
            case 1:
                quotationRecords.getPlasticsQuotationList().add(event.getQuotationListDTO());
                break;
            case 2:
                quotationRecords.getPlasticsQuotationList().set(event.getPosition(),event.getQuotationListDTO());
                break;
            case 3:
                finish();
                break;
        }

        detailItemAdapter.clear();
        detailItemAdapter.addAll(quotationRecords.getPlasticsQuotationList());

    }



    @OnClick(R.id.tv_updata)
    public void upData() {

        String neiRong = et_baojia_text.getText().toString();
//        if (TextUtils.isEmpty(neiRong)){
//            ToastUtil.showShortToast("报价内容不能为空");
//            return;
//        }
        String beizhu = et_beizhu_text.getText().toString();

        if (0== quotationRecords.getPlasticsQuotationList().size()){
            ToastUtil.showShortToast("报价要大于一条");
            return;
        }

        quotationRecords.setContent(neiRong);
        quotationRecords.setRemarks(beizhu);
        quotationRecords.setStatus("2");

        requestQuotationSave();
    }


    private void requestQuotationSave() {
        driverModel.requestQuotationSave(getContext(), quotationRecords, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    ToastUtil.showShortToast("添加成功");
                    EventBusManage.refreshBaoJiaList();
                    finish();
                } else {
                    showToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }




    public void getLastBaoJia() {
        Map<String, String> map = new HashMap<>();
//        map.put("page", page+"");

        driverModel.getLastBaoJia(this, map, true, bindLifecycle(), new ObserverResponseListener<CommonResponse<QuotationListBean.QuotationRecords>>() {
            @Override
            public void onNext(CommonResponse<QuotationListBean.QuotationRecords> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        quotationRecords = commonResponse.getData();

                        changeView();

                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }


            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    public void deleteDiaLog(int position) {
        new MaterialDialog.Builder(getContext())
                .content("确定要删除吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        detailItemAdapter.remove(position);
                        quotationRecords.getPlasticsQuotationList().remove(position);
                    }
                })
                .show();

    }


}
